package security.lesson1;

import java.util.Scanner;

public class RSA {

    public static int getD(int p,int q,int e){
        int qn,d=1;
        qn=(p-1)*(q-1);
        while(d!=0){
            if(d*e%qn==1){
                return d;
            }else{
                d++;
            }
        }
        return 0;
    }

    public static int power(int m,int a,int r){
        int[] b =new int[100];
        int length=0;
        int c=1;
        //将指数a转换为二进制
        do{
            b[length++]=a%2;
            a/=2;
        }while (a!=0);
        //记得减少一位，因为默认length++了
        length--;
        while (length>=0){
            c=(c*c)%r;
            if(b[length]==1){
                c=(c*m)%r;
            }
            length--;
        }
        return c;
    }

    public static int jieMi(int e,int n,int p){
        int q;
        q=power(p,e,n);
        return q;
    }

    public static int jiaMi(int e,int n,int p){
        int q;
        q=power(p,e,n);
        return q;
    }

    public static void main(String[] args) {
        int prime1,prime2,p;
        int d,e,n,miWen,minWen;
        System.out.println("请输入两个大的素数和公钥");
        Scanner scanner=new Scanner(System.in);
        prime1=scanner.nextInt();
        prime2=scanner.nextInt();
        e=scanner.nextInt();
        n=prime1*prime2;
        System.out.println("n为 "+n);
        d=getD(prime1,prime2,e);
        //e和n是公钥，d为私钥
        System.out.println("私钥密钥是 "+d);
        System.out.println("请输入要加密的数字串");
        while(scanner.hasNext()){
            p=scanner.nextInt();
            miWen=jiaMi(e,n,p);
            System.out.println("加密后的数值是 "+miWen);
            minWen=jieMi(d,n,miWen);
            System.out.println("解密后的数值是 "+minWen);
        }
    }
}
